package com.zheng.oss.web.service;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.Bucket;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import com.qcloud.cos.transfer.Download;
import com.qcloud.cos.transfer.TransferManager;
import com.qcloud.cos.transfer.Upload;
import com.zheng.common.util.DateUtil;
import com.zheng.oss.common.constant.OssResultConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.net.URL;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * Created by ZhangShuzheng on 2017/5/15.
 */
@Service
public class QCloudCosService {

	private static final Logger LOGGER = LoggerFactory.getLogger(QCloudCosService.class);

	@Autowired
	COSClient qcloudCosClient;
	@Autowired
	Bucket qcloudCosBucket;
	@Autowired
	Region qcloudCosRegion;
	@Autowired
	ClientConfig qcloudCosClientConfig;
	@Autowired
	COSCredentials qcloudCosCredentials;

	private TransferManager transferManager = null;
	public void QCloudCosService() {
		ExecutorService threadPool = Executors.newFixedThreadPool(32);
		// 传入一个 threadpool, 若不传入线程池, 默认 TransferManager 中会生成一个单线程的线程池。
		transferManager =new TransferManager(qcloudCosClient, threadPool);
	}

	/**
	 *
	 * @Title: uploadFile
	 * @Description:上传文件
	 */
	public String uploadFile(File localFile,String targetKey) {

		try {
			System.out.println("上传开始时间:" + DateUtil.date2Str(new Date()));
			// .....(提交上传下载请求, 如下文所属)
			// bucket 的命名规则为{name}-{appid} ，此处填写的存储桶名称必须为此格式
			String bucket = qcloudCosClient.getClientConfig().getRegion().getRegionName() + "-" + qcloudCosCredentials.getCOSAppId();
			//本地文件路径
			PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, targetKey, localFile);
			// 本地文件上传
			Upload upload = transferManager.upload(putObjectRequest);
			// 异步（如果想等待传输结束，则调用 waitForUploadResult）
			//UploadResult uploadResult = upload.waitForUploadResult();
			//同步的等待上传结束waitForCompletion
			upload.waitForCompletion();
			System.out.println("上传结束时间:" +  DateUtil.date2Str(new Date()));
			System.out.println("上传成功");
			//获取上传成功之后文件的下载地址
			URL url = qcloudCosClient.generatePresignedUrl(qcloudCosBucket.getName() + "-" + qcloudCosCredentials.getCOSAppId(), targetKey, new Date(new Date().getTime() + 5 * 60 * 10000));
			return url.getPath();
		} catch (Exception tb) {
			System.out.println("上传失败");
			tb.printStackTrace();
			LOGGER.error("上传失败",tb);
		} finally {
			// 关闭 TransferManger
			transferManager.shutdownNow();
		}
		return "";
	}

	/**
	 *
	 * @Title: downFile
	 * @Description: 下载文件
	 * @return
	 */
	public void downloadFile(File localDownFile,String targetKey) {

		try {
			String bucketName = qcloudCosBucket.getName() + "-" + qcloudCosCredentials.getCOSAppId();
			GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, targetKey);
			// 下载文件
			Download download = transferManager.download(getObjectRequest, localDownFile);
			// 等待传输结束（如果想同步的等待上传结束，则调用 waitForCompletion）
			download.waitForCompletion();
			System.out.println("下载成功");
		} catch (Exception tb) {
			System.out.println("下载失败");
			tb.printStackTrace();
			LOGGER.error("下载失败",tb);
		} finally {
			// 关闭 TransferManger
			transferManager.shutdownNow();
		}
	}

	/**
	 *
	 * @Title: deleteFile
	 * @Description: 删除文件
	 * @return
	 */
	public int deleteFile(String targetKey) {
		try {
			String bucketName = qcloudCosBucket.getName() + "-" + qcloudCosCredentials.getCOSAppId();
			qcloudCosClient.deleteObject(bucketName, targetKey);
			System.out.println("删除成功");
		} catch (Exception tb) {
			System.out.println("删除文件失败");
			tb.printStackTrace();
			LOGGER.error("删除失败",tb);
			return OssResultConstant.FAILED.code;
		}
		return OssResultConstant.SUCCESS.code;
	}
}
